package com.fivestar.finance.app.core;

import android.app.Activity;
import android.content.Context;
import android.net.ParseException;
import android.text.TextUtils;
import android.widget.Toast;

import com.fivestar.finance.app.bean.HttpResponse;
import com.fivestar.finance.app.core.mvp.BasePresenter;
import com.fivestar.finance.library.utils.NetWorkUtil;
import com.fivestar.finance.library.utils.ToastUtils;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 封装 Subscriber ， 统一处理异常 加载动画等
 *
 * @author Derek.Kidd
 * @version V1.0.0
 * @date 2016/8/17 10:30
 */
public abstract class ExSubscriber<T extends HttpResponse> extends Subscriber<HttpResponse>
        implements ProgressDialogHandler.ProgressCancelListener {

    private BasePresenter basePresenter;

    private ProgressDialogHandler mProgressDialogHandler;

    private Context context;


    public ExSubscriber(BasePresenter basePresenter, boolean isShowLoading) {

        this.basePresenter = basePresenter;
        context = (Activity) this.basePresenter
                .getMvpView();
        if (isShowLoading)
            mProgressDialogHandler = new ProgressDialogHandler(context, this, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        showProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        dismissProgressDialog();
        if (e instanceof HttpException) {//对网络异常 弹出相应的toast
            HttpException httpException = (HttpException) e;
            if (TextUtils.isEmpty(httpException.getMessage())) {
                ToastUtils.show(context, "网络异常", Toast.LENGTH_SHORT);
            } else {
                String errorMsg = httpException.getMessage();
                if (TextUtils.isEmpty(errorMsg)) {
                    ToastUtils.show(context, "网络异常", Toast.LENGTH_SHORT);
                } else {
                    ToastUtils.show(context, errorMsg, Toast.LENGTH_SHORT);
                }
            }
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {//解析异常
            //TODO
            ToastUtils.show(context, "数据解析异常", Toast.LENGTH_SHORT);
        } else if (e instanceof UnknownHostException) {
            ToastUtils.show(context, "服务器异常", Toast.LENGTH_SHORT);
        } else if (e instanceof SocketTimeoutException) {
            ToastUtils.show(context, "请求超时", Toast.LENGTH_SHORT);
        } else if (e instanceof ConnectException) {
            Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else {//未知错误
            if (NetWorkUtil.isNetworkConnected(context)) {
                ToastUtils.show(context, "内部错误", Toast.LENGTH_SHORT);
                e.printStackTrace();//对于未知错误进行打印,大部分为程序逻辑错误
            } else {
                ToastUtils.show(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT);
            }
        }
        onHttpError();
    }


    @Override
    public void onNext(HttpResponse httpResponse) {
        //TODO  解析 httpResponse
        int status = httpResponse.getStatus();
        if (0 == status) {
            onSuccess(httpResponse.getData());
        } else {
            //TODO  错误码统一处理
            onFailure(new FFException(status, httpResponse
                    .getDescribe()));
        }
    }

    public void onHttpError() {
        // do nothing by default
    }

    protected abstract void onSuccess(Object object);

    protected abstract void onFailure(FFException e);

    @Override
    public void onCompleted() {
        dismissProgressDialog();
        if (basePresenter.mCompositeSubscription != null) {
            basePresenter.mCompositeSubscription.remove(this);
        }
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG)
                    .sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG)
                    .sendToTarget();
            mProgressDialogHandler = null;
        }
    }
}
